import {Form, Input, Button, NavBar, Dialog} from 'antd-mobile'
import React from "react";
import { Link,useHistory } from "react-router-dom";
import request from "../utils/request";


export default ()=>{
    const history = useHistory();
    const ret = ()=> {
        history.push('/');
    }


    const Go = (e)=>{
        history.push('/reg');
    }



    const onFinish = ({username,password})=>{
        request.post('/login',{
            username,password
        }).then(({data})=>{

            if(data.success === true){


                if (!window.localStorage) {
                    console.log('浏览器版本太低，不支持localStorage')
                } else {
                    let storage = window.localStorage
                    storage.setItem('name', data.username)
                }

                history.push('/mine');
            }else{
                Dialog.show({
                    content: '用户名或密码错误,如果没有账号可以去注册一个',
                    closeOnAction: true,
                    actions: [
                        [
                            {
                                key: 'unlogin',
                                text: '取消登录',
                                onClick:()=>{
                                    window.location.reload()
                                }
                            },
                            {
                                key: 'reg',
                                text: '去注册',
                                bold: true,
                                onClick:()=>{
                                    Go()
                                }
                            },
                        ],
                    ],
                })
            }

        })
    }


    return (
        <div style={{position:'fixed',height:'100%',width:'100%',top:0,left:0}}>
            <Form
                layout='horizontal'
                onFinish={onFinish}
                footer={
                    <Button block
                            type='submit'
                            color='primary'
                    >
                        登录
                    </Button>
                }
            >
                <NavBar onBack={ret}>请登录</NavBar>
                <Form.Item
                    name='username'
                    label='用户名'
                    rules={[{ required: true, message: '用户名不能为空' }]}
                >
                    <Input placeholder='请输入用户名' />
                </Form.Item>
                <Form.Item
                    name='password'
                    label='密码'
                    rules={[{ required: true, message: '密码不能为空' }]}
                >
                    <Input placeholder='请输入密码' type='password' />
                </Form.Item>

            </Form>
            <div style={{padding:'10px'}}>
                没有帐户？去
                <Link to='/reg'>注册</Link>
            </div>
        </div>
    )
}